<template>
  <div class="friend-list">
    <!-- 搜索框 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索好友"
        :prefix-icon="Search"
        clearable
        @input="handleSearch"
        @clear="clearSearch"
        class="search-input"
      />
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-section">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-section">
      <el-alert
        :title="error"
        type="error"
        show-icon
        :closable="false"
      />
      <el-button @click="refreshFriends" type="primary" size="small" class="retry-btn">
        重试
      </el-button>
    </div>

    <!-- 好友列表 -->
    <div v-else class="friends-content">
      <!-- 搜索结果 -->
      <div v-if="isSearchMode" class="search-results">
        <div class="section-header">
          <span class="section-title">搜索结果 ({{ searchResults.length }})</span>
        </div>
        <div v-if="searchResults.length === 0" class="empty-state">
          <el-empty description="未找到匹配的好友" :image-size="80" />
        </div>
        <div v-else class="friend-items">
          <div
            v-for="friend in searchResults"
            :key="`search-${friend.id}`"
            class="friend-item"
            :class="{ active: currentConversationId === getConversationId(friend.id) }"
            @click="handleFriendClick(friend)"
          >
            <FriendItem
              :friend="friend"
              :unread-count="getUnreadCount(friend.id)"
              :is-selected="currentConversationId === getConversationId(friend.id)"
            />
          </div>
        </div>
      </div>

      <!-- 正常好友列表 -->
      <div v-else class="normal-list">
        <!-- 在线好友 -->
        <div v-if="onlineFriendsList.length > 0" class="friends-section">
          <div class="section-header" @click="toggleOnlineSection">
            <el-icon class="expand-icon" :class="{ expanded: showOnlineFriends }">
              <ArrowRight />
            </el-icon>
            <span class="section-title">在线好友 ({{ onlineFriendsList.length }})</span>
          </div>
          <div v-show="showOnlineFriends" class="friend-items">
            <div
              v-for="friend in onlineFriendsList"
              :key="`online-${friend.id}`"
              class="friend-item"
              :class="{ active: currentConversationId === getConversationId(friend.id) }"
              @click="handleFriendClick(friend)"
            >
              <FriendItem
                :friend="friend"
                :unread-count="getUnreadCount(friend.id)"
                :is-selected="currentConversationId === getConversationId(friend.id)"
              />
            </div>
          </div>
        </div>

        <!-- 离线好友 -->
        <div v-if="offlineFriendsList.length > 0" class="friends-section">
          <div class="section-header" @click="toggleOfflineSection">
            <el-icon class="expand-icon" :class="{ expanded: showOfflineFriends }">
              <ArrowRight />
            </el-icon>
            <span class="section-title">离线好友 ({{ offlineFriendsList.length }})</span>
          </div>
          <div v-show="showOfflineFriends" class="friend-items">
            <div
              v-for="friend in offlineFriendsList"
              :key="`offline-${friend.id}`"
              class="friend-item"
              :class="{ active: currentConversationId === getConversationId(friend.id) }"
              @click="handleFriendClick(friend)"
            >
              <FriendItem
                :friend="friend"
                :unread-count="getUnreadCount(friend.id)"
                :is-selected="currentConversationId === getConversationId(friend.id)"
              />
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="friendsList.length === 0" class="empty-state">
          <el-empty description="暂无好友" :image-size="100">
            <el-button type="primary" @click="$emit('add-friend')">
              添加好友
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowRight } from '@element-plus/icons-vue'
import { useFriendsStore } from '@/stores/friends'
import { useConversationsStore } from '@/stores/conversations'
import { useAuthStore } from '@/stores/auth'
import type { Friend } from '@/types'
import FriendItem from './FriendItem.vue'

// Props
interface Props {
  // 可以添加额外的props
}

const props = defineProps<Props>()

// Emits
interface Emits {
  (e: 'friend-selected', friend: Friend): void
  (e: 'conversation-changed', conversationId: string): void
  (e: 'add-friend'): void
}

const emit = defineEmits<Emits>()

// Stores
const friendsStore = useFriendsStore()
const conversationsStore = useConversationsStore()
const authStore = useAuthStore()

// Reactive data
const searchKeyword = ref('')
const showOnlineFriends = ref(true)
const showOfflineFriends = ref(false)
const searchTimer = ref<NodeJS.Timeout | null>(null)

// Computed properties
const isLoading = computed(() => friendsStore.isLoading)
const error = computed(() => friendsStore.error)
const friendsList = computed(() => friendsStore.friendsList)
const onlineFriendsList = computed(() => friendsStore.onlineFriendsList)
const offlineFriendsList = computed(() => friendsStore.offlineFriendsList)
const searchResults = computed(() => friendsStore.searchResultsList)
const isSearchMode = computed(() => searchKeyword.value.trim().length > 0)
const currentConversationId = computed(() => conversationsStore.currentConversationId)
const conversations = computed(() => conversationsStore.conversationsList)

// Methods
const handleSearch = (value: string) => {
  // 防抖搜索
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  
  searchTimer.value = setTimeout(async () => {
    if (value.trim()) {
      await friendsStore.searchFriends({
        keyword: value.trim(),
        page: 1,
        pageSize: 50
      })
    } else {
      friendsStore.clearSearchResults()
    }
  }, 300)
}

const clearSearch = () => {
  searchKeyword.value = ''
  friendsStore.clearSearchResults()
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
    searchTimer.value = null
  }
}

const toggleOnlineSection = () => {
  showOnlineFriends.value = !showOnlineFriends.value
}

const toggleOfflineSection = () => {
  showOfflineFriends.value = !showOfflineFriends.value
}

const refreshFriends = async () => {
  await friendsStore.refreshFriends()
}

// 获取与好友的会话ID
const getConversationId = (friendId: number): string | null => {
  const currentUserId = authStore.user?.id
  if (!currentUserId) return null
  
  const conversation = conversations.value.find(conv => 
    conv.type === 'PRIVATE' && 
    conv.participants.includes(friendId) && 
    conv.participants.includes(currentUserId)
  )
  
  return conversation?.id || null
}

// 获取与好友的未读消息数
const getUnreadCount = (friendId: number): number => {
  const conversationId = getConversationId(friendId)
  if (!conversationId) return 0
  
  const conversation = conversations.value.find(conv => conv.id === conversationId)
  return conversation?.unreadCount || 0
}

// 处理好友点击事件
const handleFriendClick = async (friend: Friend) => {
  try {
    const currentUserId = authStore.user?.id
    if (!currentUserId) return
    
    // 查找或创建私聊会话
    let conversationId = getConversationId(friend.id)
    
    if (!conversationId) {
      // 创建新的私聊会话
      const conversation = await conversationsStore.findOrCreatePrivateConversation(friend.id)
      if (conversation) {
        conversationId = conversation.id
      }
    }
    
    if (conversationId) {
      // 设置当前会话
      conversationsStore.setCurrentConversation(conversationId)
      
      // 标记会话为已读
      await conversationsStore.markConversationAsRead(conversationId)
      
      // 发出事件
      emit('friend-selected', friend)
      emit('conversation-changed', conversationId)
    }
  } catch (error) {
    console.error('Failed to handle friend click:', error)
    ElMessage.error('切换聊天失败')
  }
}

// 生命周期
onMounted(async () => {
  // 加载好友列表
  await friendsStore.loadFriends()
  
  // 加载会话列表
  await conversationsStore.loadConversations()
})

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  if (!newValue.trim()) {
    friendsStore.clearSearchResults()
  }
})

// 清理定时器
onUnmounted(() => {
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
})
</script>

<style scoped lang="scss">
.friend-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  
  .search-section {
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    
    .search-input {
      width: 100%;
    }
  }
  
  .loading-section {
    padding: 16px;
  }
  
  .error-section {
    padding: 16px;
    
    .retry-btn {
      margin-top: 12px;
      width: 100%;
    }
  }
  
  .friends-content {
    flex: 1;
    overflow-y: auto;
    
    .search-results,
    .normal-list {
      .friends-section {
        .section-header {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          background: #f5f7fa;
          border-bottom: 1px solid #ebeef5;
          cursor: pointer;
          user-select: none;
          transition: background-color 0.2s;
          
          &:hover {
            background: #ecf5ff;
          }
          
          .expand-icon {
            margin-right: 8px;
            transition: transform 0.2s;
            
            &.expanded {
              transform: rotate(90deg);
            }
          }
          
          .section-title {
            font-size: 14px;
            font-weight: 500;
            color: #606266;
          }
        }
        
        .friend-items {
          .friend-item {
            cursor: pointer;
            transition: background-color 0.2s;
            border-bottom: 1px solid #f0f0f0;
            
            &:hover {
              background: #f5f7fa;
            }
            
            &.active {
              background: #ecf5ff;
              border-left: 3px solid #409eff;
            }
            
            &:last-child {
              border-bottom: none;
            }
          }
        }
      }
    }
    
    .empty-state {
      padding: 40px 16px;
      text-align: center;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .friend-list {
    .search-section {
      padding: 12px;
    }
    
    .friends-content {
      .friends-section {
        .section-header {
          padding: 10px 12px;
          
          .section-title {
            font-size: 13px;
          }
        }
      }
    }
  }
}
</style>